<template>
  <div id="editor" />
</template>
<script>
import wangEditor from "wangeditor";
import { request, getImgSrc } from "@rabbit.do/rabbit";
export default {
  name: 'Editor',
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {

    };
  },
  mounted() {
    var E = wangEditor;
    var editor = new E('#editor');
    // 显示base图片
    editor.customConfig.uploadImgShowBase64 = true;
    // 上传图片
    editor.customConfig.customUploadImg = (files, insert) => {
      files.forEach(item => {
        this.handleRequestFile(item, insert);
      });
    };
    // 内容change事件
    editor.customConfig.onchange = (html) => {
      this.$emit("change", html);
    };
    // 创建editor
    editor.create();
    // 回显写入
    if (this.value) editor.txt.html(this.value);
  },
  methods: {
    // 自定义上传
    handleRequestFile(file, insert) {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("appId", 2);
      formData.append("type", 1);
      request({
        url: "/rabbit/file/upload",
        data: formData,
      }).then(res => {
        if (res.statusCode === 600 && res.data) {
          const str = getImgSrc(res.data.id);
          // 写入editor内容
          insert(str);
        }
      });
    },
  },
};
</script>
